package com.young.shop.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.young.domain.SysLog;
import com.young.domain.SysLogExample;
import com.young.domain.SysLogExample.Criteria;
import com.young.mapper.SysLogMapper;
import com.young.req.SysLogPageReq;
import com.young.res.SysLogPageRes;
import com.young.shop.service.SysLogService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description: 系统日志的服务类
 * @Author: kangyang
 * @Date: 2021/5/19 22:09
 **/
@Service
public class SysLogServiceImpl implements SysLogService {

  @Autowired
  private SysLogMapper sysLogMapper;

  @Override
  public PageInfo<SysLogPageRes> getSysLogPageInfo(SysLogPageReq sysLogPageReq) {
    PageInfo<SysLogPageRes> pageResPageInfo = new PageInfo<>();
    if(sysLogPageReq == null) {
      return pageResPageInfo;
    }
    Page<SysLog> page = PageHelper
        .startPage(sysLogPageReq.getCurrent(), sysLogPageReq.getSize());
    SysLogExample sysLogExample = new SysLogExample();
    Criteria criteria = sysLogExample.createCriteria();
    if(StringUtils.isNotEmpty(sysLogPageReq.getUsername())) {
      criteria.andUsernameLike("%" + sysLogPageReq.getUsername() + "%");
    }
    if(StringUtils.isNotEmpty(sysLogPageReq.getOperation())) {
      criteria.andOperationEqualTo(sysLogPageReq.getOperation());
    }
    sysLogExample.setOrderByClause("create_date desc");
    List<SysLog> sysLogs = sysLogMapper.selectByExample(sysLogExample);
    List<SysLogPageRes> sysLogPageResList = new ArrayList<>();
    for (SysLog sysLog : sysLogs) {
      SysLogPageRes sysLogPageRes = new SysLogPageRes();
      BeanUtils.copyProperties(sysLog, sysLogPageRes);
      sysLogPageResList.add(sysLogPageRes);
    }
    pageResPageInfo.setTotal(page.getTotal());
    pageResPageInfo.setPageNum(page.getPageNum());
    pageResPageInfo.setPageSize(page.getPageSize());
    pageResPageInfo.setList(sysLogPageResList);

    return pageResPageInfo;
  }

  @Override
  public void saveSysLog(SysLog sysLog) {
    int insert = sysLogMapper.insert(sysLog);
  }
}
